package com.admin.system.modules.mnt.service.impl;

import com.admin.system.modules.mnt.dto.ServerQueryDTO;
import com.admin.system.modules.mnt.entity.Server;
import com.admin.system.modules.mnt.mapper.DeployServerMapper;
import com.admin.system.modules.mnt.mapper.ServerMapper;
import com.admin.system.modules.mnt.service.ServerService;
import com.admin.system.modules.mnt.util.ExecuteShellUtil;
import com.admin.common.utils.PageResult;
import com.admin.common.utils.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;

/**
 * @author sq-lan
 */
@Service
@RequiredArgsConstructor
public class ServerServiceImpl extends ServiceImpl<ServerMapper, Server> implements ServerService {

    private final DeployServerMapper deployServerMapper;

    @Override
    public PageResult<Server> paging(ServerQueryDTO dto) {
        PageHelper.startPage(dto.getCurrent(), dto.getSize());
        List<Server> list = this.list(dto);
        return PageUtil.toPageHelper(list);
    }

    @Override
    public List<Server> list(ServerQueryDTO dto) {
        LambdaQueryWrapper<Server> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.hasText(dto.getBlurry())) {
            wrapper.and(w -> w.like(Server::getName, dto.getBlurry()).or().like(Server::getIp, dto.getBlurry()));
        }
        if (dto.getCreateTime() != null && !dto.getCreateTime().isEmpty()) {
            wrapper.between(Server::getCreateTime, dto.getCreateTime().get(0), dto.getCreateTime().get(1));
        }
        return this.list(wrapper);
    }

    @Override
    public Server getByIp(String ip) {
        return this.getOne(Wrappers.<Server>lambdaQuery().eq(Server::getIp, ip), false);
    }

    @Override
    public Boolean testConnect(Server entity) {
        ExecuteShellUtil executeShellUtil = null;
        try {
            executeShellUtil = new ExecuteShellUtil(entity.getIp(), entity.getAccount(), entity.getPassword(), entity.getPort());
            return executeShellUtil.execute("ls") == 0;
        } catch (Exception e) {
            return false;
        } finally {
            if (executeShellUtil != null) {
                executeShellUtil.close();
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(Set<Integer> ids) {
        removeByIds(ids);
        // 删除与之关联的服务
        deployServerMapper.deleteByServerIds(ids);
    }

}
